﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RazzzorTest.Models;
using RazzzorTest.Models.Login;
using System.Web.Security;

namespace RazzzorTest.Controllers
{
    public class HomeController : Controller
    {
        BlogDataContext repo = new BlogDataContext();
        //
        // GET: /Home/

        public ActionResult Index()
        {
            var home = repo.Pages.SingleOrDefault(e => e.PageName == "Home");
            ViewBag.WellcomMessage = home == null ? string.Empty : home.Content;
            var news = repo.News.Take(5).ToList();
            return View(news);
        }

        /// <summary>
        /// Get Edit 
        /// </summary>
        /// <returns>Widok strony głównej</returns>
        public ActionResult Edit()
        {
            var page = repo.Pages.FirstOrDefault(e => e.PageName == "Home");
            if (page != null)
                ViewBag.Content = page.Content;
            else
                ViewBag.Content = string.Empty;

            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(FormCollection form)
        {
            var content = form["Content"] as string;
            Page p = null;
            if ((p = repo.Pages.FirstOrDefault(e => e.PageName == "Home")) == null)
                p = new Page();

            p.PageName = "Home";
            p.Content = content;
            if (p.ID == 0)
                repo.Pages.InsertOnSubmit(p);
            repo.SubmitChanges();
            return RedirectToAction("Index");
        }

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(User _user)
        {
            if (FormsAuthentication.Authenticate(_user.Login, _user.Password))
            { return RedirectToAction("Index"); }
            ViewBag.ErrorMessage = "Niepoprawne dane";
            return View();
        }

    }
}
